<template>
  <view class="page-main">
    <!--    <view class="topbox">-->
    <!--      <image class="topimg" src="/static/banner.png"></image>-->
    <!--      <view class="imgtext"> {{ title }}</view>-->
    <!--    </view>-->
    <swiper :autoplay="false" :circular="false" :current="currentIndex" class="swipercard" next-margin="0"
            previous-margin="0" @change="eventHandle">
      <block v-for="(item, index) in newQuestionsAnswer" :key="index">
        <swiper-item class="swiperitem">
          <view class="itembox">
            <view class="contentbox">
              <view class="boxtitle tc">
                <text class="textr tc" style="text-align: center;">{{ item.title }}</text>
                <!--                <img v-if="item.img" :src="item.img" alt=""-->
                <!--                     style="object-fit: cover;width: 100%;margin-top: 30rpx">-->
              </view>
              <view v-if="item.problemType === 'SINGLE'">
                <view v-for="(self,idxs) in item.children" :key="idxs" class="boxbody" @click="singChoose(index,idxs)">
                  <view v-if="!self.slot" class="chooseitem f ac xb">

                    <view class="bodyr f ac ">
                      <!--                      <div class="mr20r" style="background: #00C853;width: 100rpx;height: 100rpx;"></div>-->
                      {{ self.answer }}
                    </view>
                    <image v-if="self.isSelect" class="sinchoose-on" mode="" src="/static/chooseon.png">
                    </image>
                    <view v-else class="sinchoose"></view>
                  </view>
                  <div v-if="self.slot" class=" chooseitem f ax xb">
                    <div class="f ac">其他： <input v-model="self.answer" type="text"
                                                   @input="(e)=>otherBlur(e.detail.value,index,idxs)"></div>
                    <image v-if="self.isSelect" class="sinchoose-on" mode="" src="/static/chooseon.png">
                    </image>
                    <view v-else class="sinchoose"></view>
                  </div>
                </view>
              </view>
              <view v-if="item.problemType === 'MULTY'">
                <view v-for="(self,idxm) in item.children" :key="idxm" class="boxbody">
                  <view class="chooseitem" @click="multyChoose(index,idxm)">
                    <image v-if="self.isSelect" class="sinchoose-on" mode="" src="/static/chooseon2.png">
                    </image>
                    <view v-else class="sinchoose sinchoose2"></view>
                    <view class="bodyr">{{ self.alias }}、{{ self.answer }}</view>
                  </view>
                </view>
              </view>

              <view v-if="item.problemType == 'QUESTION'" class="writeitem pt10r">
                <!--								<textarea class="textInfo" v-model="item.userAnswer" @input="bindTextAreaBlur(index)"-->
                <!--                          auto-height maxlength="200" placeholder="请输入"/>-->
                <input v-model="_templateName" class="textInfo"
                       placeholder="请输入"
                       style="border: 1px solid #ccc;padding: 10rpx;border-radius: 10rpx"
                       @input="bindTextAreaBlur(index)"/>
              </view>
              <div v-else>
                <slot :name="item.slot"></slot>
              </div>
            </view>
            <view class="footbtn">
              <view class="ftbtn1" @click="back(index)">上一步</view>
              <view v-if="(index + 1) < totalNum" class="ftbtn1" @click="next(index)">继续</view>
              <view v-else class="ftbtn2" @click="submitData">创建</view>
            </view>
          </view>
        </swiper-item>
      </block>
    </swiper>
  </view>
</template>

<script>
import {getLocalStorage, setLocalStorage} from "@/utils/api";

export default {
  name: 'slide-questions',
  props: {
    //问题列表数据
    dataList: {
      type: Array,
      default() {
        return []
      }
    },
    //标题
    title: {
      type: String,
      default: '测试题库名称'
    }
  },
  watch: {
    dataList: {
      deep: true,
      immediate: true,
      handler(newArr) {
        if (newArr.length) {
          this.newQuestionsAnswer = JSON.parse(JSON.stringify(newArr))
          this.totalNum = newArr.length
          this.setEmptyData()
        }
      },
    },
  },
  data() {
    return {
      totalNum: 0,
      currentIndex: 0,
      newQuestionsAnswer: [],
      formSubmitData: [], //提交所需数据
      templateName: ['', '', ''],
      _templateName: '' // 确保初始值为空
    };
  },
  mounted() {
    // 移除从本地存储获取数据
    // this.templateName = getLocalStorage('templateName') || ['', '', '']
  },
  methods: {
    //创建提交数组的数据结构
    setEmptyData() {
      this.formSubmitData = [];  // 确保清空之前的数据
      this._templateName = '';   // 重置输入框的值
      this.templateName = ['', '', '']; // 重置模板名称数组
      
      this.newQuestionsAnswer.forEach((res) => {
        let userAnswer = ''
        res.children && res.children.forEach(item => {
          if (!item.isSelect) item.isSelect = 0
          else userAnswer = item
        })
        if (res.problemType == 'QUESTION') userAnswer = res.userAnswer
        this.formSubmitData.push({
          id: res.id,
          userAnswer: userAnswer,
        })
      })
    },
    submitData() {
      for (var i = 0; i < this.formSubmitData.length; i++) {
        if (!this.formSubmitData[i].userAnswer) {
          let toast = '请完成第' + (i + 1) + '个问题后提交！'
          uni.showToast({
            title: toast,
            icon: 'none'
          })
          this.currentIndex = i
          return
        }
      }

      // 处理收集到的答案
      const templateData = {
        planName: '', // 将存储最终的模板名称
        nodes: []
      };

      // 处理答案
      const answers = this.formSubmitData.map(item => {
        if (item.id === '1') { // 主项运动
          return item.userAnswer.answer;
        }
        if (item.id === '2') { // 重点部位
          return item.userAnswer.answer;
        }
        if (item.id === '3') { // 运动目的
          return item.userAnswer.answer;
        }
        if (item.id === '4') { // 模板名称
          return item.userAnswer;
        }
        return '';
      });

      // 使用模板名称作为计划名称
      templateData.planName = answers[3] || `${answers[0]}${answers[1]}${answers[2]}`;
      
      // 添加初始节点
      templateData.nodes = [{
        purpose: answers[2], // 使用运动目的作为第一个节点的目的
        exercises: [] // 初始化空的动作数组
      }];

      console.log(templateData, "templateData");

      this.$emit("submit", templateData);
    },
    //单选事件
    singChoose(j, e) {
      if (this.newQuestionsAnswer[j].children[e].isSelect) {
        this.newQuestionsAnswer[j].children[e].isSelect = 0;
        this.formSubmitData[j].userAnswer = '';
      } else {
        for (var i = 0; i < this.newQuestionsAnswer[j].children.length; i++) {
          if (this.newQuestionsAnswer[j].children[i].isSelect) {
            this.newQuestionsAnswer[j].children[i].isSelect = 0;
          }
        }
        this.newQuestionsAnswer[j].children[e].isSelect = 1;
        this.$set(this.templateName, j, this.newQuestionsAnswer[j].children[e].answer);
        this.formSubmitData[j].userAnswer = this.newQuestionsAnswer[j].children[e];
      }
      this.newQuestionsAnswer = JSON.parse(JSON.stringify(this.newQuestionsAnswer));
    },
    //多选事件
    multyChoose(j, e) {
      this.newQuestionsAnswer[j].children[e].isSelect = this.newQuestionsAnswer[j].children[e].isSelect ^ 1
      let obj = []
      for (var i = 0; i < this.newQuestionsAnswer[j].children.length; i++) {
        if (this.newQuestionsAnswer[j].children[i].isSelect) {
          // 这块结合业务逻辑可以进行优化处理
          // 例如 只保存用户已选择答案Id等
          // obj.push(this.newQuestionsAnswer[j].children[i].id)
          obj.push(this.newQuestionsAnswer[j].children[i])
        }
      }
      this.formSubmitData[j].userAnswer = obj
      this.newQuestionsAnswer = JSON.parse(JSON.stringify(this.newQuestionsAnswer))
    },
    //富文本
    bindTextAreaBlur(index) {
      this.formSubmitData[index].userAnswer = this._templateName;
      this.$set(this.templateName, index, this._templateName);
    },
    otherBlur(e, index, idxs) {
      this.$set(this.templateName, index, e);
      this.formSubmitData[index].userAnswer.userAnswer = e;
    },   //swiper改变时
    eventHandle(e) {
      // 这块可以结合业务逻辑进行优化处理，如左右滑动切换题目时做一些提示处理等
      this.currentIndex = e.detail.current
    },
    // 上一题
    back(index) {
      if (!index) return
      this.currentIndex = index - 1
    },
    //下一题
    next(index) {
      console.log(this.formSubmitData[index].userAnswer, '////////////../')
      // for (var i = 0; i < this.formSubmitData.length; i++) {
      //   if (!this.formSubmitData[i].userAnswer) {
      //     let toast = '请完成第' + (i + 1) + '个问题！'
      //     uni.showToast({
      //       title: toast,
      //       icon: 'none'
      //     })
      //     this.currentIndex = i
      //     return
      //   }
      // }
      this.currentIndex = index + 1
    }
  }
};
</script>

<style scoped>
.page-main {
  width: 100%;
  height: 100vh;
}

.topbox {
  width: 100%;
  height: 140rpx;
  position: relative;
}

.topbox .topimg {
  width: 100%;
  height: 100%;
}

.topbox .imgtext {
  position: absolute;
  bottom: 60rpx;
  left: 58rpx;
  font-size: 36rpx;
  font-weight: normal;
  color: #FFFFFF;
  line-height: 36rpx;
  text-shadow: 0rpx 2rpx 4rpx rgba(0, 0, 0, 0.5);

}

.swipercard {
  width: 100%;
  height: 100vh;
  background: #FFFFFF;
}

.itembox {
  width: calc(100% - 96rpx);
  padding: 28rpx 48rpx;
}

.box-hd {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 4rpx dashed #f0f0f0;
  padding-bottom: 16rpx;
  padding-left: 16rpx;
}

.hdname {
  width: 400rpx;
  font-size: 28rpx;
  display: flex;
  align-items: flex-start;
  font-weight: 500;
  color: #666666;
  line-height: 40rpx;
}

.text1 {
  color: #1FA474;
  font-size: 40rpx;
  line-height: 32rpx;
}

.hdnum {
  font-size: 28rpx;
  font-weight: 400;
  color: #666666;
  line-height: 42rpx;
}

.contentbox {
  font-size: 30rpx;
  color: #333333;
  margin-top: 48rpx;
}
.textr {
  font-size: 50rpx;
  font-weight: 800;
}
.boxtitle .textl {

  width: 50rpx;
  height: 34rpx;
  background: linear-gradient(90deg, #C3FFDA 0%, #ffffff 100%);
}

.boxbody {
  /* padding-left: 40rpx; */
  line-height: 64rpx;
  margin: 16rpx 0;
}

.chooseitem {
  display: flex;
  align-items: center;
  padding: 60rpx;
  border-radius: 20rpx;
  background: #000;
  color: #fff;
  font-size: 30rpx;
}

.sinchoose {
  width: 28rpx;
  height: 28rpx;
  margin-right: 16rpx;
  border-radius: 50%;
  background: #FFFFFF;
  border: 2rpx solid #BFBDBD;
}

.sinchoose2 {
  border-radius: 6rpx;
}

.sinchoose-on {
  width: 32rpx;
  height: 32rpx;
  margin-right: 16rpx;
}

.writeitem textarea {
  min-height: 164rpx;
  margin: 24rpx auto;
  padding: 16rpx;
  border: 2rpx solid #EBEBEB;
  border-radius: 4px;
  font-size: 30rpx;
  color: #333333;
}

.footbtn {
  display: flex;
  justify-content: space-between;
  margin-top: 112rpx;
  padding: 0 24rpx;
}

.ftbtn1 {
  width: 270rpx;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border: 2rpx solid #000;
  font-size: 30rpx;
  font-weight: 500;
  color: #FFF;
  background: #000;
  border-radius: 30rpx;
}

.ftbtn2 {
  width: 270rpx;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  background: #000;
  border-radius: 30rpx;
  font-size: 30rpx;
  font-weight: 500;
  color: #FFFFFF;
}
</style>
